package org.zxb.demo.resolver;

import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.zxb.demo.annotation.MultipartFileVerify;
import org.zxb.demo.constant.FileType;
import org.zxb.demo.util.FileTypeUtil;

/**
 * 文件类型校验-允许的文件类型
 *
 * @author zxb
 * @date 2022-04-08 10:07
 **/
@Log4j2
@NoArgsConstructor
public class MultipartFileAllowValidator extends AbstractMultipartFileValidator {
    protected AbstractMultipartFileValidator delegate;

    public MultipartFileAllowValidator(AbstractMultipartFileValidator abstractMultipartFileValidator) {
        delegate = abstractMultipartFileValidator;
    }

    @Override
    @SneakyThrows
    public boolean isFileValid(MultipartFileVerify multipartFileValid, MultipartFile value) {
        FileType[] fileTypes = multipartFileValid.value();
        if (ObjectUtils.isEmpty(fileTypes)) {
            return true;
        }
        String sourceFileType = FileTypeUtil.getFileType(value.getInputStream());
        for (FileType fileType : fileTypes) {
            if (fileType.getName().equals(sourceFileType)) {
                return true;
            }
        }
        log.warn("文件类型校验失败，文件类型不在允许范围内");
        return false;
    }
}
